package org.liuping.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import org.liuping.common.utlis.R;
import org.liuping.exception.GetEmailCodeTooFastException;
import org.liuping.service.UserService;
import org.liuping.vo.UserLoginVo;
import org.liuping.vo.UserRegistryVo;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Controller
public class UserController {

    @Resource
    private UserService userService;
    /**
     *
     * @return 跳转index页面
     */
    @GetMapping("/")
    public String adminIndex(){
        return "index";
    }
    /**
     *
     * @return 跳转login页面
     */
    @GetMapping("/login")
    public String adminLogin(){

        return "login";
    }
    /**
     *
     * @return 跳转user页面
     */
    @SaCheckLogin
    @GetMapping("/user")
    public String adminUser(){

        return "user";
    }
    /**
     *
     * @return 跳转注册页面
     */
    @GetMapping("/registry")
    public String adminRegistry(){

        return "registry";
    }

    /**
     * 登录到user界面
     * 开启数据校验功能
     */
    @GetMapping("/login/in")
    public String login(@Validated UserLoginVo userLoginVo){
        //调用service实现登录功能，自动感知异常，由全局异常进行处理
        userService.login(userLoginVo);
        return "user";
    }
    /**
     * 安全退出
     */
    @GetMapping("/logout")
    public String logout(){
        //安全退出,删除redis中的token
        StpUtil.logout();
        return "login";
    }

    /**
     * 用户注册
     */
    @PostMapping("/registry/in")
    public String registry(@Validated UserRegistryVo userRegistryVo){
        userService.registry(userRegistryVo);
        //注册成功则返回登录页面进行登录
        return "login";
    }
    /**
     * ajax异步请求:发送邮箱验证码
     */
    @GetMapping("/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("email") String email) {
        try {
            userService.sendCode(email);
        } catch (GetEmailCodeTooFastException e) {
            return R.error(401,"获取验证码失败","验证码获取太快");
        }
        return R.ok();
    }
}
